﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EventModel;
using GreenPipes;
using MassTransit;
using MassTransit.ExtensionsDependencyInjectionIntegration;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace ConsumeBus
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddMvc();
            string db = Configuration.GetSection("DB")["ExamDB"];
            SugarBase._connString = db;
            services.AddSingleton<ExamTool>();
            services.AddSingleton<RedisHelper>();
            services.AddTransient<IConsumeRepository, ConsumeRepository>();

            services.AddMassTransit(c =>
            {
                c.AddConsumer<ConsumeEventHandler>();
            });
            services.AddScoped<ConsumeEventHandler>();
        }
        public static IBusControl BusControl { get; private set; }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider, IHostingEnvironment env, IApplicationLifetime lifetime)
        {
            BusControl = Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                var host = cfg.Host(new Uri(Configuration.GetSection("MQ")["Host"]), hst =>
                {
                    hst.Username(Configuration.GetSection("MQ")["UserName"]);
                    hst.Password(Configuration.GetSection("MQ")["Password"]);
                });

                // 重试
                cfg.UseRetry(ret =>
                {
                    ret.Interval(3, TimeSpan.FromSeconds(10));
                });

                cfg.ReceiveEndpoint(host, Configuration.GetSection("MQ")["Queue"], e =>
                {
                    e.LoadFrom(serviceProvider);
                });
            });

            lifetime.ApplicationStarted.Register(BusControl.Start);
            lifetime.ApplicationStopped.Register(BusControl.Stop);
        }
    }
}
